package com.ease.integration.converter;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Comment;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.ease.common.util.FileUtil;
import com.ease.common.util.JsonUtil;
import com.ease.integration.context.vo.XmlElementAnnotation;
import com.ease.integration.definition.constant.IntegrationMessageTemplateReserveKey;

public abstract class XmlElementAnnotationTemplateParser {

	private static final transient Log log = LogFactory.getLog(XmlElementAnnotationTemplateParser.class);

	public static List<XmlElementAnnotation> parse(String filename) {
		try {
			List<XmlElementAnnotation> list = new ArrayList<XmlElementAnnotation>();

			String xmlDocuments = FileUtil.readClassPathResourceToString(filename);
			String[] xmlArray = xmlDocuments.split(IntegrationMessageTemplateReserveKey.ARGUMENTS_SPLITER);
			for (int i = 0; i < xmlArray.length; i++) {
				String xmlDocument = xmlArray[i];
				int idx = xmlDocument.indexOf("=<?xml");
				Document doc = DocumentHelper.parseText(xmlDocument.substring(idx + 1));
				Element root = doc.getRootElement();
				visitTree(root, list);
			}
			return list;
		} catch (Exception e) {
			log.error(e, e);
		}

		return null;
	}

	private static void visitTree(Element root, List<XmlElementAnnotation> list) {
		for (int i = 0, size = root.nodeCount(); i < size; i++) {
			Node node = root.node(i);
			if (node instanceof Comment) {
				Comment comment = (Comment) node;
				if (comment.getText().startsWith(" {\"")) {
					XmlElementAnnotation pi = parseComment(comment);
					if (null != pi) {
						list.add(pi);
					}
				}
			} else if (node instanceof Element) {
				visitTree((Element) node, list);
			}
		}
	}

	private static XmlElementAnnotation parseComment(Comment comment) {
		XmlElementAnnotation pi = JsonUtil.unmarshal(comment.getText(), XmlElementAnnotation.class);
		return pi;
	}
}
